package segger.vasttrafik;

import org.apache.log4j.Logger;

public class API {
    private static final Logger logger = Logger.getLogger(API.class);
    
    public static final int SERVICE_LOCATION_NAME = 0;
    public static final int SERVICE_DEPARTURE = 1;

    private static final String BASE_URL = "http://api.vasttrafik.se/bin/rest.exe/";
    private static final String VERSION = "v1/";

    private static String IDENTIFIER;

    private static final API instance = new API();
    private API() {}
    
    public static API getInstance() {
        return instance;
    }
    
    public final void setIdentifier(String identifier) {
        IDENTIFIER = identifier;
    }
    
    public final URLBuilder getURLBuilder(int service) {
        // TODO json
        switch (service) {
            case SERVICE_LOCATION_NAME:
                return new URLBuilder("location.name", "input");
            case SERVICE_DEPARTURE:
                return new URLBuilder("departureBoard", "id");
            default:
                return null;
        }
    }

    class URLBuilder {
        
        private String[] keys;
        private String[] values;
        private String url;

        private URLBuilder(String service, String... params) {
            url = BASE_URL + VERSION + service + "?";

            keys = new String[params.length];
            for (int i = 0; i < params.length; i++) {
                keys[i] = params[i];
            }
        }

        public void input(String... input) {
            if (input.length != keys.length)
                return;
            values = new String[input.length];
            for (int i = 0; i < input.length; i++) {
                values[i] = input[i];
            }
        }

        public String getURL() {
            StringBuilder builder = new StringBuilder();
            builder.append(url);
            for (int i = 0; i < keys.length; i++) {
                builder.append(keys[i] + "=" + values[i]);
                builder.append("&");
            }
            builder.append("authKey=" + IDENTIFIER);
            String builtURL = builder.toString();
            logger.debug("URLBuilder.getURL(): " + builtURL);
            return builtURL;
        }
    }
}
